<?php


namespace app\api\common\auth;

class Finance
{
	public static function set($auth, $field, $number, $type, $remarks, $source)
	{
		if (!is_array($auth)) {
			$auth = \think\Db::name("app_auth_user")->where(["id" => $auth])->find();
		}
		$data = ["appid" => $auth["appid"], "uid" => $auth["id"], "field" => $field, "number" => $number, "type" => $type, "remarks" => $remarks, "after" => $type ? $auth[$field] - $number : $auth[$field] + $number, "ago" => $auth[$field], "time" => time(), "source" => $source];
		$up = \think\Db::name("app_auth_user")->where(["id" => $auth["id"]]);
		if ($field == "endtime") {
			$endtime = $number;
			$data["after"] = $endtime;
			if ($auth["endtime"] <= $endtime) {
				$data["number"] = $endtime - $auth["endtime"];
				$data["type"] = 0;
			} else {
				$data["number"] = $auth["endtime"] - $endtime;
				$data["type"] = 1;
			}
			$is_forever_auth = $auth["is_forever_auth"];
			if (\app\common\model\DefaultConfig::PerpetualTimeValue <= $endtime || \app\common\model\DefaultConfig::PerpetualTimeValue <= $number) {
				$is_forever_auth = 1;
				$endtime = \app\common\model\DefaultConfig::PerpetualTimeValue;
				$data["number"] = \app\common\model\DefaultConfig::PerpetualTimeValue;
			}
			\think\Db::name("app_auth_user")->where("id", $auth["id"])->update(["endtime" => $endtime, "is_forever_auth" => $is_forever_auth]);
		} else {
			if ($type == 0) {
				$up->setInc($field, $number);
			} else {
				$up->setDec($field, $number);
			}
		}
		return \think\Db::name("app_auth_user_finance_log")->insertGetId($data);
	}
}